import { Component, Node, sys } from "cc";
import { DEBUG } from "cc/env";

/** 日志管理 */
export class Logger {
    /**
     * 是否开启日志
     * //XHW.logg.enabled = false;不需要的情况下可以关闭日志节省性能
     */
    public static enabled: boolean = DEBUG;

    static trace(...args: any[]): void {
        if (!this.enabled) return;
        if (sys.isBrowser) {
            return console.log('【Logger】', ...args);
        }
        let msg = "";
        for (let item of args) {
            let str = "";
            switch (typeof item) {
                case "object": {
                    if (!item) {
                        str = "null";
                    } else {
                        str = this.safetyStringify(item);
                    }
                    break;
                }
                default: {
                    str = (item && item.toString()) || item;
                    break;
                }
            }
            if (str) {
                let arr = str.split("\n");
                if (arr.length > 5) {
                    str = arr.join(" ");
                }
            }
            msg = msg + " | " + str;
        }
        console.log('【Logger】', msg);
    }



    /** 安全字符串化 */
    private static safetyStringify(obj) {
        let cache = [];
        let str = JSON.stringify(obj, function (key, value) {
            if (value instanceof Component) {
                return "cc.Component(" + value.uuid + ")";
            }
            if (value instanceof Node) {
                return "cc.Node(" + value.uuid + ")";
            }
            if (typeof value === "object" && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    return; // 移除
                }
                cache.push(value); // 收集所有的值
            }
            return value;
        }, 1);
        cache = null; // 清空变量，便于垃圾回收机制回收
        return str;
    }
}